﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;

namespace CryptoFiles.Managers
{
    public static class CryptoManager
    {
        public static string GenerateHash(string input)
        {
            MD5 md5 = MD5.Create();

            byte[] hash = md5.ComputeHash(Encoding.Default.GetBytes(input));
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < hash.Length; i++)
            {
                sb.Append(hash[i].ToString("x2"));
            }
            return sb.ToString();
        }


        public static byte[] EncryptData(byte[] dataToEncrypt, string sKey)
        {
            using (MemoryStream stream = new MemoryStream())
            {
                DESCryptoServiceProvider cryptic = new DESCryptoServiceProvider();

                cryptic.Key = Encoding.ASCII.GetBytes(sKey);
                cryptic.IV = Encoding.ASCII.GetBytes(sKey);

                using (CryptoStream crStream = new CryptoStream(stream, cryptic.CreateEncryptor(), CryptoStreamMode.Write))
                {
                    crStream.Write(dataToEncrypt, 0, dataToEncrypt.Length);
                    crStream.FlushFinalBlock();

                    byte[] output = stream.ToArray();

                    return output;
                }
            }
        }


        private static byte[] ReadFully(Stream stream)
        {
            byte[] buffer = new byte[2048];
            using (MemoryStream ms = new MemoryStream())
            {
                while (true)
                {
                    int read = stream.Read(buffer, 0, buffer.Length);
                    
                    if (read <= 0)  return ms.ToArray();
                    
                    ms.Write(buffer, 0, read);
                }
            }
        }


        public static byte[] DecryptData(byte[] dataToDecrypt, string sKey)
        {
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();
           
            des.Key = Encoding.ASCII.GetBytes(sKey);
            des.IV = Encoding.ASCII.GetBytes(sKey);

            using (MemoryStream stream = new MemoryStream(dataToDecrypt))
            {
                ICryptoTransform desdecrypt = des.CreateDecryptor();

                using (CryptoStream cryptostreamDecr = new CryptoStream(stream, desdecrypt, CryptoStreamMode.Read))
                {
                    return ReadFully(cryptostreamDecr);
                }
            }
        }



        public static string GenerateKey()
        {
            DESCryptoServiceProvider desCrypto = (DESCryptoServiceProvider)DES.Create();

            return Encoding.ASCII.GetString(desCrypto.Key);
        }



    }
}
